package com.example.aiadmin.service.impl;

import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.example.aiadmin.util.AiReviewUtil;
import com.example.xwcommon.entity.Weibo;
import com.example.xwcommon.service.AiAdminService;
import com.example.xwcommon.service.WeiboService;
import com.example.xwcommon.vo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class AiAdminServiceImpl implements AiAdminService {
    @Qualifier("com.example.xwcommon.service.WeiboService")
    @Autowired
    private WeiboService weiboService;

    @Scheduled(cron = "0/30 * * * * ?")
    public void aiReviewWeiBo() throws NoApiKeyException, InputRequiredException {
        System.out.println("开始审核微博");
        Response<List<Weibo> > response = weiboService.getWeiboListByState(2);
        if(response.getCode()!=200){
            System.out.println("获取待审核微博失败");
            return;
        }
        //获取待审核列表
        List<Weibo> list = response.getData();
        if(list.isEmpty()){
            System.out.println("没有待审核微博");
            return;
        }
        StringBuilder sb = new StringBuilder();
        int i =1;
        for (Weibo weibo : list) {
            sb.append("微博"+ i +":\n"+weibo.toString());
            sb.append("\n");
            i++;
        }
        String message = sb.toString();
        AiReviewUtil reviewUtil = new AiReviewUtil();
        GenerationResult gen_result = reviewUtil.review(message);
        String result = gen_result.getOutput().getChoices().get(0).getMessage().getContent();
        System.out.println("原本result："+result+"\n");
        result = result.replaceAll("[^\\d,\\-]+", "");
        System.out.println("审核结果：\n"+result);
        String[] parts = result.split(",");
        int[] states = new int[parts.length];
        for(int j=0;j<parts.length;j++){
            if(parts[j].trim().equals("1")){
                states[j] = 1;
            }
            else if(parts[j].trim().equals("-1")){
                states[j] = -1;
            }
            else if(parts[j].trim().equals("3")){
                states[j] = 3;
            }
        }
//        for(Weibo weibo:list){
//            System.out.println("微博Id"+weibo.getWeiboId());
//        }
        for(int j=0;j<states.length;j++){
            System.out.println("微博"+ (j+1) +"审核结果："+states[j]);
            weiboService.updateState(list.get(j).getWeiboId(), states[j]);
        }
    }
}
